package com.kaoshi.myweb.webtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

/**
 * 搜索 红马jdbc 未关闭连接的代码
 * 根据 java类中，打开连接  和  关闭连接 的次数
 * 来确认代码中是否有未关闭的连接
 */
public class JavaStat {

	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("请输入要搜索代码java文件或java目录：");
		Scanner in = new Scanner(System.in);
		String filePath = in.nextLine();

		if (filePath.equals("") || filePath == null)
			filePath = "F:\\svn\\peizi\\dianjinhe\\src";

		File file = new File(filePath);
		// 根据用户输入的文件名和目录执行搜索
		codeStat(file);
	}

	public static void codeStat(File file) throws FileNotFoundException {
		if (file == null || !file.exists())
			throw new FileNotFoundException(file + "，文件不存在！");

		if (file.isDirectory()) {
			File[] files = file.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith(".java") || pathname.isDirectory();
				}
			});

			for (File target : files) {
				codeStat(target);
			}
		} else {
			BufferedReader bufr = null;
			try {
				// 将指定路径的文件与字符流绑定
				bufr = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			} catch (FileNotFoundException e) {
				throw new FileNotFoundException(file + "，文件不存在！" + e);
			}

			Set<String> list = new HashSet<String>();
			
			// 遍历文件中的每一行，并根据正则匹配的结果记录每一行匹配的结果
			String line = null;
			int lineNo = 0;
			List<Integer> connLineNo = new ArrayList<Integer>();
			List<Integer> closeLineNo = new ArrayList<Integer>();
			
			int blanceConn = 1;
			int blanceClose = 1;
			
			
			StringBuilder msg = new StringBuilder();
			try {
				while ((line = bufr.readLine()) != null) {
					lineNo++;

					if (StringUtils.isBlank(line)) {
						continue;
					}

					line = line.trim();

					if (line.startsWith("//") || line.startsWith("*")) {
						continue;
					}

					if (line.indexOf("MySQL.getConnection()") != -1 || line.indexOf("Database.getConnection()") != -1 || line.indexOf("connectionManager.getConnection()") != -1) {
						line = line.trim();
						
						if(closeLineNo.size() - connLineNo.size() >= blanceClose){
							msg.append(closeLineNo.get(connLineNo.size() - 1) + ":close代码过多\r\n");
							blanceClose++;
						}
						//System.out.println(lineNo + ":" + line);
						try {
							String[] strings = line.substring(0, line.indexOf("=")).split(" ");
							String var = strings[strings.length - 1] + ".close()";
							list.add(var);
							connLineNo.add(lineNo);
						} catch (Exception e) {
							e.printStackTrace();
						}
						continue;
					}

					for (String string : list) {
						if (line.indexOf(string) != -1) {
							if(connLineNo.size() - closeLineNo.size() > blanceConn){
								msg.append(connLineNo.get(connLineNo.size() - 2) + ":未找到close代码\r\n");
								blanceConn++;
							}
							//System.out.println(lineNo + ":" + string);
							closeLineNo.add(lineNo);
							break;
						}
					}
				}
			} catch (IOException e) {
				throw new RuntimeException("读取文件失败！" + e);
			} finally {
				try {
					bufr.close(); // 关闭文件输入流并释放系统资源
				} catch (IOException e) {
					throw new RuntimeException("关闭文件输入流失败！");
				}
			}

			if (connLineNo.size() != closeLineNo.size()) {
				System.out.println(file.getAbsolutePath() + "\r\n" + msg.toString());
			}
		}
	}
}